//
//  MyReplyViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 4/12/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import MJRefresh
import SVProgressHUD
import AVOSCloud

class MyReplyViewController: RootViewController, UITableViewDataSource, UITableViewDelegate {

    
    @IBOutlet weak var tabView: UITableView!
    
    var replyArray = [Reply]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "我的回贴"
        tabView.tableFooterView = UIView()
        
        self.tabView.register(UINib(nibName: "MainPageReplyCell", bundle: nil), forCellReuseIdentifier: "MainPageReplyCell")
        
        self.tabView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.requestData(true)
        })
        
        self.tabView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.requestData(false)
        })
        requestData(true)
    }

    func requestData(_ header: Bool) {
        SVProgressHUD.show()
        let query: AVQuery = Reply.query()
        query.includeKey(kReplyKeyUser)
        query.includeKey(kReplyKeyContentImage)
        query.includeKey(kReplyKeyCitys)
        query.includeKey(kReplyKeyTopic)
        query.includeKey("topic.contentImage")
        query.order(byDescending: "updatedAt")
        query.whereKey(kReplyKeyUser, equalTo: AVUser.current())
        query.limit = kNetPageSize
        if !header {
            let top = replyArray.last
            let date = top?.object(forKey: "updatedAt")
            if date != nil {
                query.whereKey("updatedAt", lessThan: date)
            }
        }
        
        query.findObjectsInBackground { (objects: [Any]?, error: Error?) in
            
            if error == nil && objects != nil {
                if let reply = objects as? [Reply] {
                    if header {
                        self.replyArray.removeAll()
                    }
                    self.replyArray += reply
                    self.tabView.reloadData()
                    SVProgressHUD.dismiss()
                } else {
                    SVProgressHUD.showError(withStatus: "获取列表失败")
                }
            } else {
            
                SVProgressHUD.showError(withStatus:error?.localizedDescription)
            }
            self.tabView.mj_header.endRefreshing()
            if objects != nil && (objects?.count)! < kNetPageSize {
                self.tabView.mj_footer.endRefreshingWithNoMoreData()
            } else {
                if header {
                    self.tabView.mj_footer.resetNoMoreData()
                } else {
                    self.tabView.mj_footer.endRefreshing()
                }
            }
        }
    }
    
    // MARK: UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return replyArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.fd_heightForCell(withIdentifier: "MainPageReplyCell", configuration: { (cell: Any?) in
            let mainCell = cell as? MainPageReplyCell
            let reply = self.replyArray[(indexPath as NSIndexPath).row]
            mainCell?.refreshView(reply)
        })
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MainPageReplyCell", for: indexPath) as! MainPageReplyCell
        cell.selectionStyle = .none
        let reply = replyArray[(indexPath as NSIndexPath).row]
        cell.refreshView(reply)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let reply = replyArray[(indexPath as NSIndexPath).row]
        let cirDetailVC = UIStoryboard.mainStoryboard.instantiateViewController(withIdentifier: "CirclReplyViewController") as! CirclReplyViewController;
        cirDetailVC.topic = reply.topic
        cirDetailVC.city = reply.city
        self.navigationController?.pushViewController(cirDetailVC, animated: true)
    }
}
